<template>
  <div class="user-list-container">
    <el-form :inline="true" :model="searchFrom" class="demo-form-inline">
      <el-form-item label="账单编码">
        <el-input v-model="searchFrom.billCode"></el-input>
      </el-form-item>
      <el-form-item label="商品名称">
        <el-input v-model="searchFrom.productName"></el-input>
      </el-form-item>
      <el-form-item label="供应商">
        <el-input v-model="searchFrom.proName"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doSearch">查询</el-button>
      </el-form-item>
    </el-form>

    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="billCode" label="账单编码">
      </el-table-column>
      <el-table-column prop="productName" label="商品名称">
      </el-table-column>
      <el-table-column prop="proName" label="供应商名称">
      </el-table-column>
      <el-table-column prop="totalPrice" label="商品总额">
      </el-table-column>
      <el-table-column prop="isPayment" label="是否支付">
      </el-table-column>
      <el-table-column prop="creationDate" label="创建时间">
      </el-table-column>
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button type="small" @click="handleShow(scope.$index, scope.row)">查看</el-button>
          <el-button type="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页条 -->
    <div class="pagination-block">
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pagination.currentPage"
          :page-sizes="[3, 5, 10]"
          :page-size="pagination.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pagination.total">
      </el-pagination>
    </div>

    <el-dialog title="查看账单信息" v-model="showFormVisible">
      <el-form :model="showForm">
        <el-form-item label="账单编码" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.billCode"></el-input>
        </el-form-item>
        <el-form-item label="商品名称" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.productName"></el-input>
        </el-form-item>
        <el-form-item label="类别" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.productDesc"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.productUnit"></el-input>
        </el-form-item>
        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.proName"></el-input>
        </el-form-item>
        <el-form-item label="商品单价" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.productCount"></el-input>
        </el-form-item>
        <el-form-item label="商品总额" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.totalPrice"></el-input>
        </el-form-item>
        <el-form-item label="是否支付" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.isPayment"></el-input>
        </el-form-item>
        <el-form-item label="创建时间" :label-width="formLabelWidth">
          <el-input autocomplete="off" disabled v-model="showForm.creationDate"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="showFormVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="修改账单信息" v-model="editFormVisible">
      <el-form :model="editForm" :rules="rules" ref="editFormRef">
        <el-form-item label="账单编码" :label-width="formLabelWidth">
          <el-input v-model="editForm.billCode" disabled></el-input>
        </el-form-item>
        <el-form-item label="商品编码" :label-width="formLabelWidth">
          <el-input v-model="editForm.productName"></el-input>
        </el-form-item>
        <el-form-item label="类别" :label-width="formLabelWidth">
          <el-input v-model="editForm.productDesc"></el-input>
        </el-form-item>
        <el-form-item label="单位" :label-width="formLabelWidth">
          <el-input v-model="editForm.productUnit"></el-input>
        </el-form-item>
        <el-form-item label="供应商" :label-width="formLabelWidth">
          <el-select v-model="editForm.proName" placeholder="请选择供应商" style="width: 100%">
            <el-option
              v-for="item in providerOptions"
              :key="item.proCode"
              :label="item.proName"
              :value="item.proName"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="商品单价" :label-width="formLabelWidth">
          <el-input v-model="editForm.productCount"></el-input>
        </el-form-item>
        <el-form-item label="商品总额" :label-width="formLabelWidth">
          <el-input v-model="editForm.totalPrice"></el-input>
        </el-form-item>
        <el-form-item label="是否支付" :label-width="formLabelWidth">
          <el-input v-model="editForm.isPayment"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" @click="doUpdate()">确 定</el-button>
          <el-button @click="editFormVisible = false">取 消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request';
import { updateBill, deleteBill} from "@/api/bill";

export default {
  name: 'UserList',
  setup() {
    const searchFrom = reactive({
      billCode: "",
      productName: "",
      proName: ""
    })

    const tableData = ref([])

    const pagination = reactive({
      currentPage: 1,
      pageSize : 3,
      total: 0
    })

    const showFormVisible = ref(false)
    const showForm = reactive({
      billCode: '',
      productName: '',
      proName: '',
      productDesc: '',
      productUnit: '',
      productCount: '',
      totalPrice: '',
      isPayment: '',
      createBy: '',
      creationDate: '',
    })
    const formLabelWidth = '120px'

    const editFormVisible = ref(false)
    const editForm = reactive({
      id: '', // 添加id字段
      billCode: '',
      productName: '',
      proName: '',
      productDesc: '',
      productUnit: '',
      productCount: '',
      totalPrice: '',
      isPayment: '',

    })

    const editFormRef = ref(null)
    const rules = reactive({
      productName: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
      ],
      proName: [
        { required: true, message: '请输入供应商名称', trigger: 'blur' },
        { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
      ]
    })

    const providerOptions = ref([])


    function doSearch() {
      pagination.currentPage = 1
      doList()
    }

    function fetchProviders() {
      request({
        url: '/provider/list',
        method: 'get'
        // 不需要分页参数
      }).then(resp => {
        const responseData = resp.data;
        console.log("供应商接口完整响应:", responseData);
        if (responseData.flag === true) {
          // 假设 responseData.data.list 是供应商数组
          providerOptions.value = responseData.data.list || [];
          console.log('供应商原始数组:', providerOptions.value.slice())
          console.log("账单页面下拉供应商:", providerOptions.value);
          console.log('供应商原始数组:', JSON.parse(JSON.stringify(providerOptions.value)))

        } else {
          ElMessage.error(responseData.message || '获取供应商列表失败');
          providerOptions.value = [];
        }
      }).catch(err => {
        console.error("获取供应商列表出错:", err);
        ElMessage.error('网络请求失败');
        providerOptions.value = [];
      });
    }

    function handleShow(index, row) {
      showFormVisible.value = true
      console.log(index, row)

      showForm.billCode = row.billCode
      showForm.productDesc = row.productDesc
      showForm.productName = row.productName
      showForm.productUnit = row.productUnit
      showForm.productCount = row.productCount
      showForm.totalPrice = row.totalPrice
      showForm.proName = row.proName
      showForm.isPayment = row.isPayment
      showForm.creationDate = row.creationDate

    }

    function handleEdit(index, row) {
      editFormVisible.value = true
      // 关键：设置账单ID，用于后端识别要更新哪条记录
      editForm.id = row.id
      editForm.billCode = row.billCode
      editForm.productName = row.productName
      editForm.proName = row.proName
      editForm.productDesc = row.productDesc
      editForm.productUnit = row.productUnit
      editForm.productCount = row.productCount
      editForm.totalPrice = row.totalPrice
      editForm.isPayment = row.isPayment
      editForm.creationDate = row.creationDate
      
      console.log('要编辑的账单信息:', editForm);
    }

    function doUpdate() {
      if (!editFormRef.value) {
        console.error('表单引用不存在');
        return;
      }

      // 确认ID字段存在
      if (!editForm.id) {
        console.error('账单ID缺失，无法更新');
        ElMessage.error('账单ID缺失，无法更新');
        return;
      }

      // 创建一个处理过的数据对象，确保类型正确
      const processedData = {
        id: editForm.id,
        billCode: editForm.billCode,
        productName: editForm.productName,
        proName: editForm.proName,
        productDesc: editForm.productDesc,
        productUnit: editForm.productUnit,
        productCount: editForm.productCount,
        totalPrice: editForm.totalPrice,
        isPayment: editForm.isPayment,

      };

      console.log('准备更新的账单数据:', processedData);

      editFormRef.value.validate((valid) => {
        if (valid) {
          updateBill(processedData).then(resp => {
            // 获取后端返回的实际数据
            const responseData = resp.data;
            console.log("更新账单响应:", responseData.flag);
            console.log("更新账单响应状态码:", responseData.flag)

            if (responseData.flag === true) {
              // 提示成功消息
              ElMessage({
                message: responseData.message || '更新成功',
                type: 'success'
              })
              // 关闭对话框
              editFormVisible.value = false
              // 重新请求列表数据
              doList()
            } else {
              ElMessage.error(responseData.message || '更新失败')
            }
          }).catch(err => {
            console.error("更新账单出错:", err)
            ElMessage.error('网络请求失败')
          })
        }
      })
    }

    function handleDelete(index, row) {
      ElMessageBox.confirm('此操作将永久删除该账单, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBill(row.id).then(resp => {
          // 获取后端返回的实际数据
          const responseData = resp.data;
          console.log("删除账单响应:", responseData);
          
          if (responseData.flag === true) {
            // 提示成功消息
            ElMessage({
              message: responseData.message || '删除成功',
              type: 'success'
            })
            // 重新请求最新列表数据
            pagination.currentPage = 1
            doList()
          } else {
            ElMessage.error(responseData.message || '删除失败')
          }
        }).catch(err => {
          console.error("删除账单出错:", err)
          ElMessage.error('网络请求失败')
        })
      }).catch(() => {
        // 取消操作
      })
    }

    function handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      pagination.pageSize = val
      doList()
    }

    function handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      pagination.currentPage = val
      doList()
    }

    function doList() {
      request({
        url: '/bill/list',
        method: 'get',
        params: {
          currentPage: pagination.currentPage,
          pageSize: pagination.pageSize,
          billCode: searchFrom.billCode,
          billName: searchFrom.productName,
          proName: searchFrom.proName

        }
      }).then(resp => {
        console.log("API完整响应:", resp)
        // 由于修改了拦截器，现在需要访问 resp.data 获取后端返回的实际数据
        const responseData = resp.data;
        console.log("后端返回数据:", responseData)
        
        if (responseData.flag === true) {
          // 访问 responseData.data 获取实际的业务数据
          tableData.value = responseData.data.list

          pagination.currentPage = responseData.data.currentPage
          pagination.pageSize = responseData.data.pageSize
          pagination.total = responseData.data.totalCount
        } else {
          ElMessage.error(responseData.message || '获取账单列表失败')
        }
      }).catch(err => {
        console.error("获取账单列表出错:", err)
        ElMessage.error('网络请求失败')
      })
    }



    onMounted(() => {
      doList()
      fetchProviders() 
    })

    return {
      searchFrom,
      tableData,
      pagination,
      showFormVisible,
      showForm,
      editFormVisible,
      editForm,
      rules,
      editFormRef,
      formLabelWidth,
      providerOptions,
      doSearch,
      handleShow,
      handleEdit,
      handleDelete,
      doUpdate,
      handleSizeChange,
      handleCurrentChange
    }
  }
}
</script>

<style scoped>
.user-list-container {
  padding: 20px;
}

.pagination-block {
  margin-top: 20px;
  text-align: right;
}
</style>